package rmi.write;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

public class HelloProxy implements InvocationHandler {

	private Class service;
	private String ip;
	private Integer port;

	public HelloProxy(Class service, String ip, Integer port) {
		super();
		this.service = service;
		this.ip = ip;
		this.port = port;
	}

	public Object getproxy() {
		return Proxy.newProxyInstance(service.getClassLoader(), new Class[] { service }, this);

	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		ObjectOutputStream objectOutputStream = null;
		ObjectInputStream inputStream = null;
		Socket socket = null;
		try {
			socket = new Socket(ip, port);
			RpcRequest request = new RpcRequest(args, service.getName(), method.getName());
			objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
			objectOutputStream.writeObject(request);
			objectOutputStream.flush();

			inputStream = new ObjectInputStream(socket.getInputStream());
			Object readObject = inputStream.readObject();

			return readObject;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("连接异常");
		} finally {
			if (objectOutputStream != null) {
				objectOutputStream.close();
			}
			if (inputStream != null) {
				inputStream.close();
			}

			if (socket != null) {
				socket.close();
			}

		}

	}

}
